package com.blink.curator.recipe.distributed;

import com.blink.base.BaseTestSample;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.junit.jupiter.api.Test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * <Description>分布式锁 </Description>
 * <ClassName> DistributedLockSample</ClassName>
 *
 * @Author liuxianzhao
 * @Date 2018年01月13日 18:14
 */
public class DistributedLockSample extends BaseTestSample {

    @Test
    public void testNoLock() {
        final CountDownLatch down = new CountDownLatch(1);
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        down.await();
                    } catch (Exception e) {
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS");
                    String orderNo = sdf.format(new Date());
                    logger.info("生成的订单号是 : " + orderNo);
                }
            }).start();
        }
        down.countDown();
        sleep();
    }


    @Test
    public void testHasLock() {
        final String lock_path = "/curator_recipes_lock_path";
        CuratorFramework client = getZkCurator();
        client.start();
        final CountDownLatch down = new CountDownLatch(1);
        for (int i = 0; i < 1000; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    InterProcessMutex lock = new InterProcessMutex(client, lock_path);
                    try {
                        down.await();
                        lock.acquire();
                    } catch (Exception e) {
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS");
                    String orderNo = sdf.format(new Date());
                    logger.info("生成的订单号是 : " + orderNo);
                    try {
                        lock.release();
                    } catch (Exception e) {
                    }
                }
            }).start();
        }
        down.countDown();
        sleep();
    }
}
